import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

/**
 * A production rule in parser grammar: <A> : <B> | alpha1 | alpha2
 * 
 * @author Chen Chen
 * 
 */
public class ProductionRule {
	public String leftHandSide;
	public List<List<String>> rightHandSide = new ArrayList<List<String>>();

	/**
	 * Constructs a grammar statement from a string
	 * 
	 * @param stmt
	 * @throws Exception
	 */
	public ProductionRule(String stmt) throws Exception {
		String[] items = stmt.split(Pattern.quote(":"));
		if (items.length == 2) {
			leftHandSide = items[0].trim();
			String[] entries=items[1].split(Pattern.quote("|"));
			for(String entry:entries){
				List<String> e=new ArrayList<String>();
				String[] terminals=entry.trim().split(Pattern.quote(" "));
				for(String t :terminals)
					if(t.trim().length()!=0)
						e.add(t.trim());
				rightHandSide.add(e);
			}
		} else {
			throw new Exception("illegal grammar: "+stmt) {};
		}
	}
	
	public String toString(){
		StringBuilder out=new StringBuilder();
		out.append(leftHandSide);
		out.append(" : ");
		
		for(List<String> e:rightHandSide){
			for(String t:e){
				out.append(' ');
				out.append(t);
				out.append(' ');
			}
			out.append(" | ");
		}
		out.delete(out.length()-2, out.length());
		return out.toString();
		
	
	
		
	}

}
